from pprint import pprint

import yaml

from common.GetFilePath import filePath


class YamlUtil(object):
    def __init__(self, file_dir, file_name):
        self.file_dir = file_dir
        self.file_name = file_name

    def read_yaml(self):
        with open(filePath(self.file_dir, self.file_name), 'r', encoding='utf-8') as f:
            return list(yaml.safe_load_all(f))

    def clear_yaml(self, data):
        with open(filePath(self.file_dir, self.file_name), 'w', encoding='utf-8') as W_f:
            yaml.dump(data, stream=W_f, allow_unicode=True)

    def write_yaml(self, data):
        # 1.判断当前yaml文件是否存在要写入的键，如果存在，覆盖该键，如果不存在则新增
        # 2.yaml文件长度为0，表示该yaml文件为空
        if len(self.read_yaml()) == 0:
            with open(filePath(self.file_dir, self.file_name), 'a', encoding='utf-8') as W_f:
                yaml.dump(data, stream=W_f, allow_unicode=True)
        else:
            commom_yaml = self.read_yaml()[0]
            for key, value in data.items():
                commom_yaml[key] = value
            self.clear_yaml(commom_yaml)


if __name__ == '__main__':
    # print(YamlUtil('config', 'config_user.yaml').read_yaml()[0]["ip"])
    #
    # YamlUtil('data', 'common.yaml').write_yaml({'Person': 'person12', 'ID': '18'})
    print(YamlUtil('data', 'common.yaml').read_yaml()[0]['Device']["serialNumber"])


